<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .item {
        display: flex;
        align-items: center;
        justify-content: space-around;
        font-size: 24px;
      }
      .total {
        font-size: 24px;
        text-align: right;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <div class="item" v-for="(item, index) in list" :key="index">
        <div class="name">{{item.name}}</div>
        <div class="price">{{item.price}}</div>
        <div class="num">
          <button @click="add(item)">+</button>
          <span>{{item.num}}</span>
          <button @click="reduce(item)">-</button>
        </div>
      </div>
      <!-- reduce
         返回值=数组.reduce((prev,item)=>....,初始值)
    -->
      <div class="total">总价:{{total}}</div>
    </div>
    <script src="./vue.js"></script>
    <script>
      new Vue({
        el: '#app',
        data: {
          list: [
            {
              name: '西瓜',
              price: 3,
              num: 4
            },
            {
              name: '香蕉',
              price: 2,
              num: 5
            },
            {
              name: '苹果',
              price: 6,
              num: 7
            }
          ]
        },
        computed: {
          total () {
            // return this.list.reduce((prev, item) => {
            //   return prev + item.price * item.num
            // }, 0)
            let _total = 0
            this.list.forEach(item => {
              _total += item.price * item.num
            })
            return _total
          }
        },
        methods: {
          add (item) {
            item.num++
          },
          reduce (item) {
            item.num--
            if (item.num < 0) {
              item.num = 0
            }
          }
        }
      })
    </script>
  </body>
</html>
